package com.atguigu.tingshu.search.service.impl;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.FieldValue;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch._types.aggregations.Aggregate;
import co.elastic.clients.elasticsearch._types.aggregations.LongTermsBucket;
import co.elastic.clients.elasticsearch._types.query_dsl.BoolQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.core.search.Suggestion;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.album.client.AlbumInfoFeignClient;
import com.atguigu.tingshu.album.client.CategoryFeignClient;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.util.PinYinUtils;
import com.atguigu.tingshu.model.album.*;
import com.atguigu.tingshu.model.search.AlbumInfoIndex;
import com.atguigu.tingshu.model.search.AttributeValueIndex;
import com.atguigu.tingshu.model.search.SuggestIndex;
import com.atguigu.tingshu.query.search.AlbumIndexQuery;
import com.atguigu.tingshu.search.repository.AlbumIndexRepository;
import com.atguigu.tingshu.search.repository.SuggestIndexRepository;
import com.atguigu.tingshu.search.service.SearchService;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.atguigu.tingshu.vo.search.AlbumInfoIndexVo;
import com.atguigu.tingshu.vo.search.AlbumSearchResponseVo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.suggest.Completion;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;


@Slf4j
@Service
@SuppressWarnings({"all"})
public class SearchServiceImpl implements SearchService {


    @Autowired
    private AlbumInfoFeignClient albumInfoFeignClient;

    @Autowired
    private CategoryFeignClient categoryFeignClient;

    @Autowired
    private UserInfoFeignClient userInfoFeignClient;

    //  定义接口：继承 ElasticsearchRepository 接口
    @Autowired
    private AlbumIndexRepository albumIndexRepository;

    @Autowired
    private SuggestIndexRepository suggestIndexRepository;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private ElasticsearchClient elasticsearchClient;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void upperAlbum(Long albumId) {
        //  需要远程调用获取数据，并将数据赋值给AlbumInfoIndex;
        AlbumInfoIndex albumInfoIndex = new AlbumInfoIndex();
        //  属性赋值：
        CompletableFuture<AlbumInfo> albumInfoCompletableFuture = CompletableFuture.supplyAsync(() -> {
            Result<AlbumInfo> infoResult = albumInfoFeignClient.getAlbumInfo(albumId);
            //  判断infoResult 不为空
            Assert.notNull(infoResult, "远程调用失败");
            AlbumInfo albumInfo = infoResult.getData();
            Assert.notNull(albumInfo, "远程调用获取albumInfo失败");
            BeanUtils.copyProperties(albumInfo, albumInfoIndex);
            //  属性数据; 通过专辑Id 查找属性Id ，属性值Id;
            List<AlbumAttributeValue> albumAttributeValueVoList = albumInfo.getAlbumAttributeValueVoList();
            //  循环遍历;
            List<AttributeValueIndex> attributeValueIndexList = albumAttributeValueVoList.stream().map(albumAttributeValue -> {
                //  创建对象
                AttributeValueIndex attributeValueIndex = new AttributeValueIndex();
                //  属性赋值:
                attributeValueIndex.setAttributeId(albumAttributeValue.getAttributeId());
                attributeValueIndex.setValueId(albumAttributeValue.getValueId());
                return attributeValueIndex;
            }).collect(Collectors.toList());
            albumInfoIndex.setAttributeValueIndexList(attributeValueIndexList);
            //  返回数据
            return albumInfo;
        }, threadPoolExecutor).exceptionally(ex -> {
            System.out.println(ex.getMessage());
            return new AlbumInfo();
        });

        //  获取分类数据
        CompletableFuture<Void> categoryCompletableFuture = albumInfoCompletableFuture.thenAcceptAsync(albumInfo -> {
            //  分类 一级分类Id，二级分类Id，三级分类Id; albumInfo.getCategory3Id(); 找 base_category_view 中的一级，二级分类Id;
            Result<BaseCategoryView> categoryViewResult = categoryFeignClient.getCategoryView(albumInfo.getCategory3Id());
            Assert.notNull(categoryViewResult, "远程调用获取分类视图失败");
            BaseCategoryView baseCategoryView = categoryViewResult.getData();
            albumInfoIndex.setCategory1Id(baseCategoryView.getCategory1Id());
            albumInfoIndex.setCategory2Id(baseCategoryView.getCategory2Id());
        }, threadPoolExecutor).exceptionally(ex -> {
            System.out.println(ex.getMessage());
            return null;
        });
        CompletableFuture<Void> userCompletableFuture = albumInfoCompletableFuture.thenAcceptAsync(albumInfo -> {
            //  用户: 用户自己上传，那必然是登录的用户Id，如果是管理员，那么就应该是不同的用户Id;
            Result<UserInfoVo> userInfoResult = userInfoFeignClient.getUserInfo(albumInfo.getUserId());
            Assert.notNull(userInfoResult, "远程调用获取用户信息失败");
            UserInfoVo userInfoVo = userInfoResult.getData();
            //  判断
            Assert.notNull(userInfoVo, "远程调用获取");
            albumInfoIndex.setAnnouncerName(userInfoVo.getNickname());
        }, threadPoolExecutor).exceptionally(ex -> {
            System.out.println(ex.getMessage());
            return null;
        });
        //  统计数据：播放量，订阅量，购买量，评论量，评分，热门度; album_stat 留作业！
        albumInfoIndex.setPlayStatNum(new Random().nextInt(100000));
        albumInfoIndex.setBuyStatNum(new Random().nextInt(100000));
        albumInfoIndex.setCommentStatNum(new Random().nextInt(100000));
        albumInfoIndex.setSubscribeStatNum(new Random().nextInt(100000));
        albumInfoIndex.setHotScore((double) new Random().nextInt(10000));

        //  通常：get方法只调用一次! 应该将方法放在最后;
        try {
            System.out.println("category:" + categoryCompletableFuture.get());
            System.out.println("user:" + userCompletableFuture.get());
            if (ObjectUtils.isEmpty(albumInfoCompletableFuture.get())) {
                log.info("远程调用失败");
                return;
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        //  多任务组合：
        CompletableFuture.allOf(
                albumInfoCompletableFuture,
                categoryCompletableFuture,
                userCompletableFuture
        ).join();
        //  将这个 albumInfoIndex 插入到es中
        log.info("将数据插入到es中");
        albumIndexRepository.save(albumInfoIndex);
        //  保存提词库!
        SuggestIndex suggestIndex = new SuggestIndex();
        //  赋值：专辑标题;
        suggestIndex.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        suggestIndex.setTitle(albumInfoIndex.getAlbumTitle());
        suggestIndex.setKeyword(new Completion(new String[]{albumInfoIndex.getAlbumTitle()}));
        suggestIndex.setKeywordPinyin(new Completion(new String[]{PinYinUtils.toHanyuPinyin(albumInfoIndex.getAlbumTitle())}));
        suggestIndex.setKeywordSequence(new Completion(new String[]{PinYinUtils.getFirstLetter(albumInfoIndex.getAlbumTitle())}));
        suggestIndexRepository.save(suggestIndex);
        //  赋值：专辑简介
        SuggestIndex suggestIndexIntro = new SuggestIndex();
        suggestIndexIntro.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        suggestIndexIntro.setTitle(albumInfoIndex.getAlbumIntro());
        suggestIndexIntro.setKeyword(new Completion(new String[]{albumInfoIndex.getAlbumIntro()}));
        suggestIndexIntro.setKeywordPinyin(new Completion(new String[]{PinYinUtils.toHanyuPinyin(albumInfoIndex.getAlbumIntro())}));
        suggestIndexIntro.setKeywordSequence(new Completion(new String[]{PinYinUtils.getFirstLetter(albumInfoIndex.getAlbumIntro())}));
        suggestIndexRepository.save(suggestIndexIntro);
        //  赋值: 作者

    }

    @Override
    public List<AlbumInfoIndex> findRankingList(Long category1Id, String ranking) {
        //  获取排行榜
        List<AlbumInfoIndex> list = (List<AlbumInfoIndex>) redisTemplate.opsForHash().get(RedisConstant.RANKING_KEY_PREFIX + category1Id, ranking);
        return list;
    }

    @Override
    public void updateLatelyAlbumRanking() {
        //  获取到所有的一级分类数据;
        Result<List<BaseCategory1>> baseCategory1Result = categoryFeignClient.findAllCategory1();
        //  判断;
        Assert.notNull(baseCategory1Result, "远程调用获取一级分类失败");
        List<BaseCategory1> baseCategory1List = baseCategory1Result.getData();
        Assert.notNull(baseCategory1List, "远程调用获取一级分类失败");
        //  循环遍历;
        for (BaseCategory1 baseCategory1 : baseCategory1List) {
            //  声明一个数组或集合来存储五个排序的维度;
            String[] rankingDimensionArray = new String[]{"hotScore", "playStatNum", "subscribeStatNum", "buyStatNum", "commentStatNum"};
            for (String rankingDimension : rankingDimensionArray) {
                //  执行dsl语句查询数据
                SearchResponse<AlbumInfoIndex> searchResponse = null;
                try {
                    searchResponse = elasticsearchClient.search(s -> s.index("albuminfo")
                                    .query(q -> q.term(t -> t.field("category1Id").value(baseCategory1.getId())))
                                    .sort(st -> st.field(f -> f.field(rankingDimension).order(SortOrder.Desc)))
                            ,
                            AlbumInfoIndex.class);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                //  获取到排序之后的数据;
                List<AlbumInfoIndex> albumInfoIndexList = searchResponse.hits().hits().stream().map(Hit::source).collect(Collectors.toList());
                //  将数据存储到缓存;
                redisTemplate.opsForHash().put(RedisConstant.RANKING_KEY_PREFIX + baseCategory1.getId(), rankingDimension, albumInfoIndexList);
            }
        }
    }

    @Override
    public List<String> completeSuggest(String keyword) {
        //  1.  根据用户输入的检索数据，从es中获取数据集合；并返回给用户;
        SearchResponse<SuggestIndex> searchResponse = null;
        try {
            searchResponse = elasticsearchClient.search(s -> s.index("suggestinfo")
                            .suggest(s1 -> s1.suggesters("keyword-suggest", s2 -> s2
                                            .prefix(keyword)
                                            .completion(c -> c
                                                    .field("keyword")
                                                    .skipDuplicates(true)
                                                    .fuzzy(f -> f.fuzziness("auto"))
                                                    .size(10)))
                                    .suggesters("keywordPinyin-suggest", s2 -> s2
                                            .prefix(keyword)
                                            .completion(c -> c
                                                    .field("keywordPinyin")
                                                    .skipDuplicates(true)
                                                    .fuzzy(f -> f.fuzziness("auto"))
                                                    .size(10)
                                            ))
                                    .suggesters("keywordSequence-suggest", s2 -> s2
                                            .prefix(keyword)
                                            .completion(c -> c
                                                    .field("keywordSequence")
                                                    .skipDuplicates(true)
                                                    .fuzzy(f -> f.fuzziness("auto"))
                                                    .size(10)
                                            ))
                            )
                    ,
                    SuggestIndex.class);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //  获取集合数据; 数据都在options;
        List<String> list = new ArrayList<>();
        list.addAll(getSuggestionTitle(searchResponse, "keyword-suggest"));
        list.addAll(getSuggestionTitle(searchResponse, "keywordPinyin-suggest"));
        list.addAll(getSuggestionTitle(searchResponse, "keywordSequence-suggest"));
        //  返回数据
        return list;
    }

    public Collection<String> getSuggestionTitle(SearchResponse<SuggestIndex> searchResponse, String suggest) {
        //  获取提词库中的数据:
        List<Suggestion<SuggestIndex>> suggestionList = searchResponse.suggest().get(suggest);
        //  判断集合不为空
        if (!CollectionUtils.isEmpty(suggestionList)) {
            //  循环遍历集合
            for (Suggestion<SuggestIndex> suggestIndexSuggestion : suggestionList) {
                //  获取数据;
                List<String> list = suggestIndexSuggestion.completion().options().stream().map(option -> {
                    String title = option.source().getTitle();
                    return title;
                }).collect(Collectors.toList());
                //  返回集合数据；
                return list;
            }
            ;
        }
        //  默认返回
        return new ArrayList<>();
    }


    @Override
    public List<Map<String, Object>> channel(Long category1Id) {
        //  频道页数据：
        //  1.  获取到一级分类下对应的三级分类Id数据;
        Result<List<BaseCategory3>> baseCategory3ResultList = categoryFeignClient.findTopBaseCategory3(category1Id);
        //  判断
        Assert.notNull(baseCategory3ResultList, "远程调用获取三级分类数据失败");
        List<BaseCategory3> baseCategory3List = baseCategory3ResultList.getData();
        //  将这个集合baseCategory3List 转换为map 集合; key=category3Id; value=BaseCategory3
        Map<Long, BaseCategory3> category3Map = baseCategory3List.stream().collect(Collectors.toMap(BaseCategory3::getId, baseCategory3 -> baseCategory3));
        //  判断
        Assert.notNull(baseCategory3List, "远程调用获取三级分类数据失败");
        List<Long> category3IdList = baseCategory3List.stream().map(BaseCategory3::getId).collect(Collectors.toList());
        //  执行dsl语句获取结果集  value<List<FieldValue>> 而 category3IdList的泛型是 <Long>
        //  需要将category3IdList集合中的数据转换为 List<FieldValue>集合
        List<FieldValue> valueList = category3IdList.stream().map(category3Id -> FieldValue.of(category3Id)).collect(Collectors.toList());
        SearchResponse<AlbumInfoIndex> searchResponse = null;
        try {
            searchResponse = elasticsearchClient.search(s -> s.index("albuminfo")
                            .query(q -> q.bool(b -> b.filter(f -> f.terms(t -> t.field("category3Id").terms(t1 -> t1.value(valueList))))))
                            .aggregations("agg_category3Id", a -> a.terms(t -> t.field("category3Id"))
                                    .aggregations("agg_topSix", a1 -> a1.topHits(t1 -> t1.size(6).sort(st -> st.field(f -> f.field("hotScore").order(SortOrder.Desc)))))
                            )
                    ,
                    AlbumInfoIndex.class);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //  从结果集中专辑集合数据; 从聚合中获取数据
        Aggregate aggregate = searchResponse.aggregations().get("agg_category3Id");
        //  尝试打印数据
        //  创建一个list<map> 集合;
        List<Map<String, Object>> listMap = aggregate.lterms().buckets().array().stream().map(bucket -> {
            Map<String, Object> map = new HashMap<>();
            //  获取三级分类Id
            long category3Id = bucket.key();
            //  获取专辑集合数据
            Aggregate aggTopSix = bucket.aggregations().get("agg_topSix");
            List<AlbumInfoIndex> albumInfoIndexList = aggTopSix.topHits().hits().hits().stream().map(hit -> {
                //  获取source 数据;
                String data = hit.source().toString();
                AlbumInfoIndex albumInfoIndex = JSONObject.parseObject(data, AlbumInfoIndex.class);
                return albumInfoIndex;
            }).collect(Collectors.toList());
            //  根据三级分类Id 获取到三级分类对象
            map.put("baseCategory3", category3Map.get(category3Id));
            map.put("list", albumInfoIndexList);
            return map;
        }).collect(Collectors.toList());
        //  返回数据
        return listMap;
    }

    @Override
    public AlbumSearchResponseVo search(AlbumIndexQuery albumIndexQuery) {
        //  1.生成dsl语句; 2.执行dsl语句； 3.返回结果;
        SearchRequest searchRequest = this.queryBuildDsl(albumIndexQuery);
        //  执行dsl 语句：
        SearchResponse<AlbumInfoIndex> searchResponse = null;
        try {
            searchResponse = elasticsearchClient.search(searchRequest, AlbumInfoIndex.class);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //  进行数据类型转换：只给list 赋值了;
        AlbumSearchResponseVo searchResponseVo = this.parseResultData(searchResponse);
        searchResponseVo.setTotal(searchResponse.hits().total().value());
        searchResponseVo.setPageSize(albumIndexQuery.getPageSize());
        searchResponseVo.setPageNo(albumIndexQuery.getPageNo());
        //  设置总页数; 10 3 4; 9 3 3
        //        searchResponseVo.setTotalPages(searchResponseVo.getTotal() % albumIndexQuery.getPageSize() == 0 ?
        //                searchResponseVo.getTotal() / albumIndexQuery.getPageSize() :
        //                searchResponseVo.getTotal() / albumIndexQuery.getPageSize() + 1);
        Long totalPages = (searchResponseVo.getTotal() + searchResponseVo.getPageSize() - 1) / searchResponseVo.getPageSize();
        searchResponseVo.setTotalPages(totalPages);
        //  返回对象
        return searchResponseVo;
    }

    /**
     * 解析结果数据
     *
     * @param searchResponse
     * @return
     */
    public AlbumSearchResponseVo parseResultData(SearchResponse<AlbumInfoIndex> searchResponse) {
        /*
            private List<AlbumInfoIndexVo> list = new ArrayList<>();
            private Long total;//总记录数
            private Integer pageSize;//每页显示的内容
            private Integer pageNo;//当前页面
            private Long totalPages;
         */
        //  创建对象
        AlbumSearchResponseVo albumSearchResponseVo = new AlbumSearchResponseVo();
        //  存储的是专辑列表集合; List<AlbumInfoIndexVo> list hits().hits().source
        List<AlbumInfoIndexVo> albumInfoIndexVoList = searchResponse.hits().hits().stream().map(hit -> {
            //  创建对象
            AlbumInfoIndexVo albumInfoIndexVo = new AlbumInfoIndexVo();
            //  赋值:
            AlbumInfoIndex albumInfoIndex = hit.source();
            BeanUtils.copyProperties(albumInfoIndex, albumInfoIndexVo);
            //  判断当前专辑标题是否有高亮;
            if (null != hit.highlight().get("albumTitle")) {
                //  获取高亮的标题;
                String albumTitle = hit.highlight().get("albumTitle").get(0);
                albumInfoIndexVo.setAlbumTitle(albumTitle);
            }
            //  返回数据
            return albumInfoIndexVo;
        }).collect(Collectors.toList());
        albumSearchResponseVo.setList(albumInfoIndexVoList);
        //  返回对象
        return albumSearchResponseVo;
    }

    /**
     * 构建dsl语句
     *
     * @param albumIndexQuery
     * @return
     */
    public SearchRequest queryBuildDsl(AlbumIndexQuery albumIndexQuery) {
        //  通过Builder() 创建对象：
        SearchRequest.Builder searchRequestBuilder = new SearchRequest.Builder();
        searchRequestBuilder.index("albuminfo");
        //  query->bool
        BoolQuery.Builder boolQuerybuilder = new BoolQuery.Builder();
        //  检索的入口：根据关键词：
        if (!StringUtils.isEmpty(albumIndexQuery.getKeyword())) {
            boolQuerybuilder.should(s -> s.match(m -> m.field("albumTitle").query(albumIndexQuery.getKeyword())))
                    .should(s -> s.match(m -> m.field("albumIntro").query(albumIndexQuery.getKeyword())))
                    .should(s -> s.match(m -> m.field("announcerName").query(albumIndexQuery.getKeyword())));
            //  设置高亮
            searchRequestBuilder.highlight(h -> h.fields("albumTitle", f -> f.preTags("<span style=color:red>").postTags("</span>")));
        }
        //  检索的第二个入口：分类：一级分类，二级分类，三级分类;
        if (!StringUtils.isEmpty(albumIndexQuery.getCategory1Id())) {
            boolQuerybuilder.filter(f -> f.term(t -> t.field("category1Id").value(albumIndexQuery.getCategory1Id())));
        }
        if (!StringUtils.isEmpty(albumIndexQuery.getCategory2Id())) {
            boolQuerybuilder.filter(f -> f.term(t -> t.field("category2Id").value(albumIndexQuery.getCategory2Id())));
        }
        if (!StringUtils.isEmpty(albumIndexQuery.getCategory3Id())) {
            boolQuerybuilder.filter(f -> f.term(t -> t.field("category3Id").value(albumIndexQuery.getCategory3Id())));
        }
        //  根据属性与属性值进行过滤;
        List<String> attributeList = albumIndexQuery.getAttributeList();
        //  判断集合是否为空
        if (!CollectionUtils.isEmpty(attributeList)) {
            //  循环遍历： 属性id:属性值id
            for (String attr : attributeList) {
                //  将attr 进行分割：
                String[] split = attr.split(":");
                //  判断
                if (null != split && split.length == 2) {
                    boolQuerybuilder.filter(f -> f.nested(n -> n.path("attributeValueIndexList")
                            .query(q -> q.bool(b -> b.must(m -> m.match(m1 -> m1.field("attributeValueIndexList.attributeId").query(split[0])))
                                    .must(m -> m.match(m1 -> m1.field("attributeValueIndexList.valueId").query(split[1])))
                            ))
                    ));
                }
            }
        }
        //  排序：排序（综合排序[1:desc] 播放量[2:desc] 发布时间[3:desc]；asc:升序 desc:降序）
        String order = albumIndexQuery.getOrder();
        if (!StringUtils.isEmpty(order)) {
            //  分割：
            String[] split = order.split(":");
            if (null != split && split.length == 2) {
                String field = "";
                //  判断：
                switch (split[0]) {
                    case "1":
                        field = "hotScore";
                        break;
                    case "2":
                        field = "playStatNum";
                        break;
                    case "3":
                        field = "createTime";
                        break;
                }
                //  设置排序字段：与排序规则；
                String finalField = field;
                searchRequestBuilder.sort(s -> s.field(f -> f.field(finalField).order("asc".equals(split[1]) ? SortOrder.Asc : SortOrder.Desc)));
            }
        }
        //  分页：
        int from = (albumIndexQuery.getPageNo() - 1) * albumIndexQuery.getPageSize();
        searchRequestBuilder.from(from);
        searchRequestBuilder.size(albumIndexQuery.getPageSize());
        BoolQuery boolQuery = boolQuerybuilder.build();
        //        Query.Builder builder = new Query.Builder();
        //        Query query = builder.build();
        //  query{};
        searchRequestBuilder.query(boolQuery._toQuery());
        SearchRequest searchRequest = searchRequestBuilder.build();
        System.out.println("dsl:\t" + searchRequest.toString());
        //  返回对象；
        return searchRequest;
    }

    @Override
    public void lowerAlbum(Long albumId) {
        //  删除
        albumIndexRepository.deleteById(albumId);
    }
}
